package cn.ainit.sys.models;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ainit.bj.bjxt.BJTopics;
import cn.ainit.bj.flow.BjFlowService;
import cn.ainit.common.ReturnObject;
import cn.ainit.model.ModelReturnObj;
import cn.ainit.sys.dz.entity.SysDzSource;
import cn.ainit.sys.framework.FrameworkService;
import cn.ainit.sys.framework.entity.ComButtons;
import cn.ainit.sys.framework.entity.SysButtons;
import cn.ainit.sys.framework.entity.SysColumns;
import cn.ainit.sys.menu.MenuController;
import cn.ainit.sys.menu.SessionCont;
import cn.ainit.sys.menu.SysFunctions;
import cn.ainit.sys.query.datastore.DataStore;
import cn.ainit.sys.query.entity.DataGridReceiveParams;
import cn.ainit.sys.query.entity.QueryJson;
import cn.ainit.sys.utils.DateTimeStr;


@Controller
@RequestMapping("/singlePages")
public class SingleController {
	private SingleService singleService;
	@Resource
	public void setSingleService(SingleService singleService) {
		this.singleService = singleService;
	}
	
	private FrameworkService frameworkService;
	@Resource
	public void setFrameworkService(FrameworkService frameworkService) {
		this.frameworkService = frameworkService;
	}
	
	private BjFlowService bjFlowService;
	@Resource
	public void setBjFlowService(BjFlowService bjFlowService) {
		this.bjFlowService = bjFlowService;
	}
	/**
	 * 单录单界面模板调用的controller方法
	 * @param dsId  datastore和column
	 * @param butnId
	 * @param type
	 * @param staticWebUrl
	 * @param initFunc
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-13 下午03:54:18
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/squeryFun")
	public String squery(ModelReceiveObj modelReceiveObj,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			String dsId = modelReceiveObj.getDsId();
			
			if(dsId==null|| dsId==""){
				System.out.println("SingleController L.202 加载页面的时候DsId传入有误，必须修改");
			}
			
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			ModelReturnObj modelReturnObj = new ModelReturnObj();
			//加载公用的按钮
			String butnId="";
			if (modelReceiveObj.getFlag().equals("1")) {	 //如果是1 则为查询窗口的公用的按钮
				butnId="queryButns";
			}else if(modelReceiveObj.getFlag().equals("2")){ //如果是2 则为详情或修改窗口的公用的按钮
				butnId="aiuComButns";
			}else{
				System.out.println("#SingleController 102 获取方式参数不对modelReceiveObj.getFlag()为空");
			}
			//加载公用的按钮的集合
			List list = this.singleService.combutnListRight(butnId,dsId,uid.toString());
			
			//加载个性化的按钮的集合
			List listTmp1 = this.singleService.butnListRight(modelReceiveObj.getDsId(),dsId,uid.toString(),modelReceiveObj.getFlag());
		
			list.addAll(listTmp1);
			Collections.sort(list,new Comparator<Map<String,Object>>(){  
				public int compare(Map<String, Object> o1,
						Map<String, Object> o2) {
					Integer num1 = Integer.parseInt(o1.get("ORDERNUM")==null?"999":o1.get("ORDERNUM")+"");
					Integer num2 = Integer.parseInt(o2.get("ORDERNUM")==null?"999":o2.get("ORDERNUM")+"");
					return num1.compareTo(num2);  
				}  
	        }); 
			DataStore dataStore = this.singleService.getDataStore(modelReceiveObj.getDsId());
			modelReturnObj.setMenuId(modelReceiveObj.getMenuId());   //子系统的Id
			modelReturnObj.setFuncId(modelReceiveObj.getFuncId());	 //模块的Id
			modelReturnObj.setButnList(list);   			//共用的按钮
		//	modelReturnObj.setPreButnList(listTmp1);  		//个性化的按钮
			modelReturnObj.setDsId(modelReceiveObj.getDsId());
			modelReturnObj.setInitFunc(modelReceiveObj.getInitFunc()!=null?modelReceiveObj.getInitFunc():"");
			modelReturnObj.setJsUrl(dataStore.getUrlJs()!=null?dataStore.getUrlJs():"");
			modelReturnObj.setPanelTitle(dataStore.getPanelTitle());
			modelReturnObj.setPrefix(dataStore.getPrefix());
			modelReturnObj.setStaticWebUrl(modelReceiveObj.getStaticWebUrl());
			modelReturnObj.setType(modelReceiveObj.getType());
			modelReturnObj.setAinitFunc(modelReceiveObj.getAinitFunc());
			modelReturnObj.setKeyValues(modelReceiveObj.getKeyValues());
			modelReturnObj.setChoice(modelReceiveObj.getChoice());
			modelReturnObj.setAoru(modelReceiveObj.getAoru()); //添加界面还是详情界面的标志位
			modelReturnObj.setWinitFunc(modelReceiveObj.getWinitFunc()!=null?modelReceiveObj.getWinitFunc():"");
			modelReturnObj.setWainitFunc(modelReceiveObj.getWainitFunc()!=null?modelReceiveObj.getWainitFunc():"");
			modelReturnObj.setTotalFlag(dataStore.getTotalFlag());
			request.setAttribute("m",modelReturnObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (modelReceiveObj.getJspWebUrl() == null || modelReceiveObj.getJspWebUrl().equals("")) {
			modelReceiveObj.setJspWebUrl("/model/single/squery");
		}
		return modelReceiveObj.getJspWebUrl();
	}
	/**
	 * 主明细时返回不同jsp的controller方法
	 * @param modelReceiveObj
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-14 下午03:28:39
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/mqueryFun")
	public String sadd(ModelReceiveObj modelReceiveObj,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			String dsId = modelReceiveObj.getDsId();
			if(dsId==null|| dsId==""){
				System.out.println("SingleController L.267 加载页面的时候DsId传入有误，必须修改");
			}
			String zhuDsId=dsId.split(";")[0];   //主表的Dsid
			String mxDsId=dsId.split(";")[1];   //明细的dsId
			//判断使用哪个模板 (0:左右主明细的模板      1:一对多的模板      2:上下主明细的模板)
			if(modelReceiveObj.getMoro()==null ||("").equals(modelReceiveObj.getMoro())){  
				modelReceiveObj.setMoro("0");
			}
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			ModelReturnObj modelReturnObj = new ModelReturnObj();
			String butnId = "";
			String[] colIds = modelReceiveObj.getDsId().split(";");
			DataStore dataStore = this.singleService.getDataStore(colIds[0]);
			if (modelReceiveObj.getFlag().equals("1")) { //如果是1 则为查询窗口的按钮
				butnId="queryButns";
			}else if(modelReceiveObj.getFlag().equals("2")){ //如果是2 则为详情或修改窗口的按钮
				butnId="aiuComButns";
			}else{
				System.out.println("modelReceiveObj.getFlag() 获取值有误，请及时修改    #L168");
			}
			//加载公用的按钮的集合
			List list = this.singleService.combutnListRight(butnId,zhuDsId,uid.toString());
			
			//加载个性化的按钮的集合
			List listTmp1 = this.singleService.butnListRight(zhuDsId,zhuDsId,uid.toString(),modelReceiveObj.getFlag());
			
			//加载明细界面的按钮
			List mxButnList=new ArrayList();
			if("aiuComButns".equals(butnId)){
				mxButnList = this.singleService.butnListRight(mxDsId,mxDsId,uid.toString(),modelReceiveObj.getFlag());
			}
			list.addAll(listTmp1);
			Collections.sort(list,new Comparator<Map<String,Object>>(){  
				public int compare(Map<String, Object> o1,
						Map<String, Object> o2) {
					Integer num1 = Integer.parseInt(o1.get("ORDERNUM")==null?"999":o1.get("ORDERNUM")+"");
					Integer num2 = Integer.parseInt(o2.get("ORDERNUM")==null?"999":o2.get("ORDERNUM")+"");
					return num1.compareTo(num2);  
				}  
	        });
			
			modelReturnObj.setMenuId(modelReceiveObj.getMenuId());   //子系统的Id
			modelReturnObj.setFuncId(modelReceiveObj.getFuncId());	 //模块的Id
			modelReturnObj.setMxButnList(mxButnList);   //明细中按钮
			modelReturnObj.setButnList(list); 			//通用的主表按钮集合
		//	modelReturnObj.setPreButnList(listTmp1);  	//加载个性化的通用的集合
			modelReturnObj.setDsId(modelReceiveObj.getDsId());
			modelReturnObj.setInitFunc(modelReceiveObj.getInitFunc()!=null?modelReceiveObj.getInitFunc():"");
			modelReturnObj.setJsUrl(dataStore.getUrlJs()!=null?dataStore.getUrlJs():"");
			modelReturnObj.setPanelTitle(dataStore.getPanelTitle());
			modelReturnObj.setPrefix(dataStore.getPrefix());
			modelReturnObj.setStaticWebUrl(modelReceiveObj.getStaticWebUrl());
			modelReturnObj.setType(modelReceiveObj.getType());
			modelReturnObj.setAinitFunc(modelReceiveObj.getAinitFunc());
			modelReturnObj.setKeyValues(modelReceiveObj.getKeyValues());
			modelReturnObj.setChoice(modelReceiveObj.getChoice());
			modelReturnObj.setAoru(modelReceiveObj.getAoru());
			modelReturnObj.setDzObjList(loadDzInfo(modelReceiveObj.getDsId())); //加载对照信息
			modelReturnObj.setPksList(loadManyPks(modelReceiveObj.getDsId(),""));//加载主外键
			modelReturnObj.setWinitFunc(modelReceiveObj.getWinitFunc()!=null?modelReceiveObj.getWinitFunc():"");
			modelReturnObj.setWainitFunc(modelReceiveObj.getWainitFunc()!=null?modelReceiveObj.getWainitFunc():"");
			modelReturnObj.setTotalFlag(dataStore.getTotalFlag());
			modelReturnObj.setMoro(modelReceiveObj.getMoro());
			request.setAttribute("m",modelReturnObj);
		} catch (Exception e) {
			System.out.println(modelReceiveObj.getDsId().toCharArray());
			e.printStackTrace();
		}                                                                               
		if (modelReceiveObj.getJspWebUrl() == null || modelReceiveObj.getJspWebUrl().equals("")) {
			modelReceiveObj.setJspWebUrl("/model/masterD/mquery");
		}
		return modelReceiveObj.getJspWebUrl(); 
	}
	
	
	
	/**
	 * 加载对照信息
	 * @param dsId
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-29 下午06:34:53
	 */
	public List loadDzInfo(String dsId) throws Exception{
		List objAcode = new ArrayList();
		objAcode = singleService.loadDzInfo(dsId);
		return objAcode;
	}
	
	
	
	/**
	 * 根据dsId（只用dsId的第一个） 查询主表的数据 返回主表的数据
	 * @param modelReceiveObj
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-4-25 上午08:58:53
	 */
	@RequestMapping("/infoData")
	@ResponseBody
	public ModelReturnObj allinfo(ModelReceiveObj modelReceiveObj,HttpServletRequest request,HttpSession session) throws Exception{
		ModelReturnObj modelReturnObj = new ModelReturnObj();
		List queryRow = new ArrayList();
		String[] configS = modelReceiveObj.getKeyValues().split(";");
		String[] dsIds = modelReceiveObj.getDsId().split(";");
		DataStore dataStore = this.singleService.getDataStore(dsIds[0]);
		//权限控制
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录 SingleController L.138");
		}
		String sql = singleService.formatSql(dsIds[0],dataStore.getSqlText(),uid == null?"":uid.toString());
		//权限控制结束
		if (dataStore != null){
			StringBuffer sqlBuffer = new StringBuffer("select * from ("+sql+") QUERYTMP where 1 = 1  ");
			String[] pks;
			for (int i = 0; i < configS.length; i++) {
				pks = configS[i].split("\\-");
				if (pks.length == 2) {
					sqlBuffer.append(" AND "+pks[0]+"='"+pks[1]+"' ");
				}else if(pks.length>2){
					//获取第一个横线  
					Integer index=configS[i].indexOf("-");
					String pkName=configS[i].substring(0,index);
					String pkVal=configS[i].substring(index+1);
					sqlBuffer.append(" AND "+pkName+"='"+pkVal+"' ");
				}else{
					System.out.println("===========================SingleController  #306 加载详情界面的数据错误 ");
				}
			}
			queryRow =this.singleService.queryRowBySql(sqlBuffer.toString());
		}
		modelReturnObj.setQueryRow(queryRow); 
		return modelReturnObj;
	}
	
	/**
	 * 打开详情界面所访问的Controller方法   双击的那条数据
	 * @param modelReceiveObj
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-14 下午03:55:55
	 */
	@RequestMapping("/sinfoData")
	@ResponseBody
	public ModelReturnObj sinfo(ModelReceiveObj modelReceiveObj,HttpServletRequest request,HttpSession session) throws Exception{
		ModelReturnObj modelReturnObj = new ModelReturnObj();
		List queryRow = new ArrayList();
		String[] configS = modelReceiveObj.getKeyValues().split(";");
		DataStore dataStore = this.singleService.getDataStore(modelReceiveObj.getDsId());
		modelReturnObj.setIskmPrems(dataStore.getIskmPrems());
		//权限控制
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录 SingleController L.138");
		}
		String sql = singleService.formatRowSql(modelReceiveObj.getDsId(),dataStore.getSqlText(),uid == null?"":uid.toString());
	
		//权限控制结束
		if (dataStore != null) {
			StringBuffer sqlBuffer = new StringBuffer("select * from ("+sql+") QUERYTMP where 1 = 1  ");
			String[] pks;
			for (int i = 0; i < configS.length; i++) {
				pks = configS[i].split("\\-");
				if (pks.length == 2) {
					sqlBuffer.append(" AND "+pks[0]+"='"+pks[1]+"' ");
				}else if(pks.length>2){
					//获取第一个横线  
					Integer index=configS[i].indexOf("-");
					String pkName=configS[i].substring(0,index);
					String pkVal=configS[i].substring(index+1);
					sqlBuffer.append(" AND "+pkName+"='"+pkVal+"' ");
				}else{
					System.out.println("===========================SingleController  #347 加载详情界面的数据错误 ");
				}
			}
			queryRow =this.singleService.queryRowBySql(sqlBuffer.toString());
		}
		SysFunctions funObj=this.bjFlowService.getSysFun(modelReceiveObj.getDsId());
		String winitFunc="";   //详情页面的回调函数
		String ainitFunc="";	//添加页面的回调函数
		//../singlePages/mqueryFun?dsId=ds_yz_print_explain1;ds_yz_print_explain_item1&type=4;3;6&staticWebUrl=&initFunc=&ainitFunc=quHideButnM&flag=1&winitFunc=bindExp
		if(funObj!=null){
			if(!"".equals(funObj.getUrl().trim())&&funObj.getUrl().lastIndexOf("winitFunc=")!=-1){
				String str=funObj.getUrl().substring(funObj.getUrl().lastIndexOf("winitFunc="));
				int strIndex=str.indexOf("&");
				if(strIndex==-1){
					winitFunc=str.substring("winitFunc=".length());
				}else{
					if((funObj.getUrl().indexOf("winitFunc=")+1)==strIndex){
						winitFunc="";
					}
					else{
						winitFunc=str.substring("winitFunc=".length(),strIndex);
					}
				}
			}
			
			if(funObj.getUrl()!=null&&!"".equals(funObj.getUrl().trim())&&funObj.getUrl().lastIndexOf("ainitFunc=")!=-1){
				String str=funObj.getUrl().substring(funObj.getUrl().indexOf("ainitFunc="));
				int strIndex=str.indexOf("&");
				if(strIndex==-1){
					ainitFunc=str.substring("ainitFunc=".length());
				}else{
					if((funObj.getUrl().indexOf("ainitFunc=")+1)==strIndex){
						ainitFunc="";
					}
					else{
						ainitFunc=str.substring("ainitFunc=".length(),strIndex);
					}
				}
			}
			
		}
		modelReturnObj.setFuncId(funObj.getMenuid());   //funcId
		modelReturnObj.setWinitFunc(winitFunc);   //详情页面的回调函数
		modelReturnObj.setAinitFunc(ainitFunc);   //添加页面的回调函数
		modelReturnObj.setQueryRow(queryRow);
		return modelReturnObj;
	}
	
	/***
	 * 返回DG表格的主键field
	 * @param colId
	 * @param type
	 * @param request
	 * @return
	 * @author Xuzq
	 * @date 2014-3-14 下午04:05:01
	 */
	public String loadPks(String colId,String type) throws Exception{
		StringBuffer pks = new StringBuffer("");
		try {
			List<SysColumns> columns = singleService.loadColumns(colId, type);
			for (int i = 0; (columns != null) && (i <  columns.size()); i++) {
				if (columns.get(i)!=null && columns.get(i).getPrimaryKey()!= null && columns.get(i).getPrimaryKey().equals("T")) {
					if (!pks.toString().equals("")) {
						pks.append(";");
					}
					pks.append(columns.get(i).getName());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pks.toString();
	}
	
	

	/**
	 * 打开详情界面所访问的Controller方法   双击的那条数据  （主明细）
	 * @param modelReceiveObj
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-14 下午03:55:55
	 */
	@RequestMapping("/mDataMaD")
	@ResponseBody
	public ModelReturnObj minfoMaster(ModelReceiveObj modelReceiveObj,HttpServletRequest request,HttpSession session) throws Exception{
		ModelReturnObj modelReturnObj = new ModelReturnObj();
		List queryRow = new ArrayList();
		List masterRow = new ArrayList(); 
		List itemRows = new ArrayList();
		List footerList = new ArrayList();
		List  noCopyColnListMx=new ArrayList();
		String[] dsIds = modelReceiveObj.getDsId().split(";");
		String[] configS = modelReceiveObj.getKeyValues().split(";");
		DataStore dataStore = this.singleService.getDataStore(dsIds[0]);
		modelReturnObj.setIskmPrems(dataStore.getIskmPrems());
		if(dsIds[1]==null){
			System.out.println("明细的dsid获取有误");
		}
		DataStore dataStore1 = this.singleService.getDataStore(dsIds[1]);
		List<SysColumns> fks = this.singleService.findFksByDsid(dsIds[1]);
		List<Map<String, Object>> pks = this.singleService.findPksByDsid(dsIds[0]);
		//权限控制
		Object uid = session.getAttribute(SessionCont.uid);
		if (uid == null || "".equals(uid.toString())) {
			System.out.println("用户未登录 SingleController L.138");
		}
		String sql = singleService.formatRowSql(dsIds[0],dataStore.getSqlText(),uid == null?"":uid.toString());
		String sql1 = singleService.formatSql(dsIds[1],dataStore1.getSqlText(),uid == null?"":uid.toString());
		//权限控制结束
		StringBuffer countSql = new StringBuffer();
		if (dataStore != null && dataStore1 != null) {
			if("3".equals(modelReceiveObj.getAoru())){
				//获取明细中不可复制的列
				noCopyColnListMx=singleService.returnNCopyList(dsIds[1]);
				modelReturnObj.setNoCopyColnListMx(noCopyColnListMx);  //明细中不可复制的列
			}
			StringBuffer sqlBuffer = new StringBuffer("select * from ("+sql+") QUERYTMP where 1 = 1  ");
			StringBuffer itemSql = new StringBuffer("select * from ("+sql1+") QUERYTMP where 1 = 1 ");
			
			//获取主表sql
			String[] pkParams;
			for (int i = 0; i < configS.length; i++) {
				pkParams = configS[i].split("\\-");
				if (pkParams.length == 2) {
					sqlBuffer.append(" AND "+pkParams[0]+"='"+pkParams[1]+"' ");
				}else if(pkParams.length>2){
					//获取第一个横线  
					Integer index=configS[i].indexOf("-");
					String pkName=configS[i].substring(0,index);
					String pkVal=configS[i].substring(index+1);
					sqlBuffer.append(" AND "+pkName+"='"+pkVal+"' ");
				}else{
					System.out.println("===========================SingleController  #490加载详情界面的数据错误 ");
				}
			}
			//获取主表数据
			masterRow =this.singleService.queryRowBySql(sqlBuffer.toString());
			//获取明细表sql
			StringBuffer whereStr = new StringBuffer();
			String fkName = "";
			String pkName = "";
			for (int i = 0; i < fks.size(); i++) {
				fkName = fks.get(i).getJavaProperyRecourded();
				pkName = pks.get(i).get("JAVA_PROPERTY_RECORDED").toString();
				whereStr.append(" and "+fkName +"='"+((Map<String, String>)masterRow.get(0)).get(pkName)+"'");
			}
			itemSql.append(whereStr);
			//获取明细表数据
			itemRows = this.singleService.queryRowBySql(itemSql.toString());
			queryRow.add(masterRow);
			queryRow.add(itemRows);
		}
		
		SysFunctions funObj=this.bjFlowService.getSysFun(modelReceiveObj.getDsId());
		String winitFunc="";   //详情页面的回调函数
		String ainitFunc="";	//添加页面的回调函数
		//../singlePages/mqueryFun?dsId=ds_yz_print_explain1;ds_yz_print_explain_item1&type=4;3;6&staticWebUrl=&initFunc=&ainitFunc=quHideButnM&flag=1&winitFunc=bindExp
		if(funObj!=null){
			if(!"".equals(funObj.getUrl().trim())&&funObj.getUrl().lastIndexOf("winitFunc=")!=-1){
				String str=funObj.getUrl().substring(funObj.getUrl().lastIndexOf("winitFunc="));
				int strIndex=str.indexOf("&");
				if(strIndex==-1){
					winitFunc=str.substring("winitFunc=".length());
				}else{
					if((funObj.getUrl().indexOf("winitFunc=")+1)==strIndex){
						winitFunc="";
					}
					else{
						winitFunc=str.substring("winitFunc=".length(),strIndex);
					}
				}
			}
			if(funObj.getUrl()!=null&&!"".equals(funObj.getUrl().trim())&&funObj.getUrl().lastIndexOf("ainitFunc=")!=-1){
				String str=funObj.getUrl().substring(funObj.getUrl().indexOf("ainitFunc="));
				int strIndex=str.indexOf("&");
				if(strIndex==-1){
					ainitFunc=str.substring("ainitFunc=".length());
				}else{
					if((funObj.getUrl().indexOf("ainitFunc=")+1)==strIndex){
						ainitFunc="";
					}
					else{
						ainitFunc=str.substring("ainitFunc=".length(),strIndex);
					}
				}
			}
		}

		//明细是否加入合计值
		if("T".equals(dataStore1.getTotalFlag())) {
			if("ds_fx_MonthSX_item1".equals(dsIds[1])) {
				List footRows = frameworkService.execSql(dataStore1.getTotalSql() + " and CM_ID = '" + ((Map)masterRow.get(0)).get("CM_ID") + '\'');
				if (footRows != null && footRows.size() > 0) {
					modelReturnObj.setFooter(footRows);
				}
			}
		}

	
		modelReturnObj.setFuncId(funObj.getMenuid());   //funcId
		modelReturnObj.setWinitFunc(winitFunc);   //详情页面的回调函数
		modelReturnObj.setAinitFunc(ainitFunc);   //添加页面的回调函数
		modelReturnObj.setQueryRow(queryRow);
		return modelReturnObj;
	}


	/**
	 * 一对多的请求方法
	 * @param modelReceiveObj
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-20 下午02:36:11
	 */
	@RequestMapping("/oqueryFun")
	public String oaddFun(ModelReceiveObj modelReceiveObj,HttpServletRequest request) throws Exception{
		try {
			ModelReturnObj modelReturnObj = new ModelReturnObj();
			String butnId = "";
			if (modelReceiveObj.getFlag().equals("1")) { //如果是1 则为查询窗口的按钮
				butnId="queryButns";
			}else if(modelReceiveObj.getFlag().equals("2")){ //如果是2 则为详情或修改窗口的按钮
				butnId="aiuComButns";
			}
			String[] butA =  butnId.split(";");
			List list = new ArrayList(); 
			for(int i = 0; i < butA.length; i++){
				List<ComButtons> listTmp = this.singleService.combutnList(butA[i]);
				list.add(listTmp);
			}
			if(modelReceiveObj.getButnId()!= null &&  !modelReceiveObj.getButnId().equals("")){
				String[] butnB = modelReceiveObj.getButnId().split(";");
				List butnList = new ArrayList(); 
				for(int w = 0; w < butnB.length; w++){
					List<SysButtons> listTmp = this.singleService.butnList(butnB[w]);
					butnList.add(listTmp !=null?listTmp:new ArrayList());
				}
				modelReturnObj.setPreButnList(butnList);
			}
			String[] colIds = modelReceiveObj.getDsId().split(";");
			List titles = new ArrayList();
			DataStore dataStore = this.singleService.getDataStore(colIds[0]);
			for (int j = 1; j < colIds.length; j++) {
				DataStore ds = this.singleService.getDataStore(colIds[j]);
				titles.add(ds.getPanelTitle());
			}
			modelReturnObj.setButnList(list);
			modelReturnObj.setDsId(modelReceiveObj.getDsId());
			modelReturnObj.setInitFunc(modelReceiveObj.getInitFunc()!=null?modelReceiveObj.getInitFunc():"");
			modelReturnObj.setJsUrl(dataStore.getUrlJs()!=null?dataStore.getUrlJs():"");
			modelReturnObj.setPanelTitle(dataStore.getPanelTitle());
			modelReturnObj.setPrefix(dataStore.getPrefix());
			modelReturnObj.setStaticWebUrl(modelReceiveObj.getStaticWebUrl());
			modelReturnObj.setType(modelReceiveObj.getType());
			modelReturnObj.setAinitFunc(modelReceiveObj.getAinitFunc());
			modelReturnObj.setKeyValues(modelReceiveObj.getKeyValues());
			modelReturnObj.setItems(dataStore.getItems());
			modelReturnObj.setChoice(modelReceiveObj.getChoice());
			modelReturnObj.setTitles(titles);
			modelReturnObj.setAoru(modelReceiveObj.getAoru());
			//加载对照信息
			modelReturnObj.setDzObjList(loadDzInfo(modelReceiveObj.getDsId()));
			//加载主外键
			modelReturnObj.setPksList(loadManyPks(modelReceiveObj.getDsId(),""));
			request.setAttribute("m",modelReturnObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (modelReceiveObj.getJspWebUrl() == null || modelReceiveObj.getJspWebUrl().equals("")) {
			modelReceiveObj.setJspWebUrl("/model/onetoM/oquery");
		}
		return modelReceiveObj.getJspWebUrl(); 
	}
	/**
	 * 加载一对多的主表和明细表的数据
	 * @param modelReceiveObj
	 * @param request
	 * @return
	 * @throws Exception
	 * @author wyang
	 * @date : 2014-3-20 下午02:16:44
	 */
	@RequestMapping("/oDataRow")
	@ResponseBody
	public ModelReturnObj oinfoOnetoM(ModelReceiveObj modelReceiveObj,HttpServletRequest request) throws Exception{
		ModelReturnObj modelReturnObj = new ModelReturnObj();
		
		List queryRow = new ArrayList();
		List masterRow = new ArrayList(); 
		List<DataStore> dataStores = new ArrayList<DataStore>();
		List<List<SysColumns>> manyfks = new ArrayList<List<SysColumns>>();//List<SysColumns> fks
		String[] dsIds = modelReceiveObj.getDsId().split(";");
		String[] configS = modelReceiveObj.getKeyValues().split(";");
		//得到所有的dataStore
		for (int i = 0; i < dsIds.length; i++) {
			DataStore dataStore = this.singleService.getDataStore(dsIds[i]);
			dataStores.add(dataStore==null?(new DataStore()):dataStore);
		}
		if(dataStores != null && dataStores.size()>0){
			StringBuffer sqlBuffer = new StringBuffer("select * from ("+dataStores.get(0).getSqlText()+") QUERYTMP where 1 = 1  ");
			String[] pkParams;
			for (int i = 0; i < configS.length; i++) {
				pkParams = configS[i].split("\\-");
				if (pkParams.length == 2) {
					sqlBuffer.append(" AND "+pkParams[0]+"='"+pkParams[1]+"' ");
				}else if(pkParams.length>2){
					//获取第一个横线  
					Integer index=configS[i].indexOf("-");
					String pkName=configS[i].substring(0,index);
					String pkVal=configS[i].substring(index+1);
					sqlBuffer.append(" AND "+pkName+"='"+pkVal+"' ");
				}else{
					System.out.println("===========================SingleController  #664 加载详情界面的数据错误 ");
				}
			}
			String fkName = "";
			masterRow =this.singleService.queryRowBySql(sqlBuffer.toString());
			queryRow.add(masterRow);
			for (int k = 1; k < dataStores.size(); k++) {
				List<SysColumns> fks = this.singleService.findFksByDsid(dsIds[k]);
				manyfks.add(fks);
				StringBuffer itemSql = new StringBuffer("select * from ("+dataStores.get(k).getSqlText()+") QUERYTMP where 1 = 1 ");
				for (int e = 0; e < manyfks.get(k-1).size(); e++) {
					StringBuffer whereStr = new StringBuffer();
					
					fkName = manyfks.get(k-1).get(e).getJavaProperyRecourded();
					whereStr.append(" and "+fkName +"='"+((Map<String, String>)masterRow.get(0)).get(fkName)+"'");
					itemSql.append(whereStr);
					List itemRows = this.singleService.queryRowBySql(itemSql.toString());
					queryRow.add(itemRows ==null?(new ArrayList()):itemRows);
					
				}
			}
		}
		modelReturnObj.setQueryRow(queryRow);
		return modelReturnObj;
	}
	/**
	 * 查询主表和明细表的主键
	 * @param colId
	 * @param type
	 * @param request
	 * @return
	 * @author wyang
	 * @date : 2014-3-18 上午10:30:34
	 */
//	@RequestMapping("/loadManyPks")
//	@ResponseBody
	public List loadManyPks(String colId,String type){
		StringBuffer pks = new StringBuffer("");
		List pksList = new ArrayList();
		try {
			String[] colIds = colId.split(";");
			List<List<SysColumns>> listCol = new ArrayList<List<SysColumns>>();
			
			for (int j = 0; j < colIds.length; j++) {
				List<SysColumns> columns = singleService.loadColumns(colIds[j], type);
				columns = columns==null?new ArrayList<SysColumns>():columns;
				listCol.add(columns);
			}
			for (int i = 0; (listCol != null) && (i <  listCol.size()); i++) {
				for (int k = 0; k < listCol.get(i).size(); k++) {
					pks = new StringBuffer();
					if (listCol.get(i)!=null && listCol.get(i).get(k).getPrimaryKey()!= null &&listCol.get(i).get(k).getPrimaryKey().equals("T")) {
						if (!pks.toString().equals("")) {
							pks.append(";");
						}
						pks.append(listCol.get(i).get(k).getName());
						pksList.add(pks);
					}
				}
			}
//			for(int k=0;k<pksList.size();k++){
//				
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pksList;
	}
	//数据挖掘封装************************************************************************
	/***
	 * 通用查询列表
	 * @param modelReceiveObj
	 * @param request
	 * @return
	 * @throws Exception
	 * @author Xuzq
	 * @date 2014-3-20 下午05:00:29
	 */
	@RequestMapping("/genFun")
	public String genQuery(ModelReceiveObj modelReceiveObj,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			ModelReturnObj modelReturnObj = new ModelReturnObj();
			String dsId = modelReceiveObj.getDsId();
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 SingleController L.138");
			}
			String[] butA =  modelReceiveObj.getButnId().split(";");
			List list = new ArrayList(); 
			for(int i = 0; i < butA.length; i++){
//				List<SysButtons> listTmp = this.singleService.butnListRight(butA[i], dsId, uid.toString());
				List listTmp = this.singleService.butnList(butA[i]);
				list.add(listTmp);
			}
			DataStore dataStore = this.singleService.getDataStore(modelReceiveObj.getDsId());
			modelReturnObj.setButnList(list);
			modelReturnObj.setDsId(modelReceiveObj.getDsId());
			modelReturnObj.setInitFunc(modelReceiveObj.getInitFunc()!=null?modelReceiveObj.getInitFunc():"");
			modelReturnObj.setJsUrl(dataStore.getUrlJs()!=null?dataStore.getUrlJs():"");
			modelReturnObj.setPanelTitle(dataStore.getPanelTitle());
			modelReturnObj.setPrefix(dataStore.getPrefix());
			modelReturnObj.setStaticWebUrl(modelReceiveObj.getStaticWebUrl());
			modelReturnObj.setType(modelReceiveObj.getType());
			modelReturnObj.setAinitFunc(modelReceiveObj.getAinitFunc());
			modelReturnObj.setKeyValues(modelReceiveObj.getKeyValues());
			request.setAttribute("m",modelReturnObj);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (modelReceiveObj.getJspWebUrl() == null || modelReceiveObj.getJspWebUrl().equals("")) {
			modelReceiveObj.setJspWebUrl("/models/single/squery");
		}
		String url=modelReceiveObj.getJspWebUrl();
		return modelReceiveObj.getJspWebUrl();//"/models/single/squery";
	}
	/***
	 * 测试保存数据  赋时间和Double 有问题
	 * @param bjTopics
	 * @param dsId
	 * @param request
	 * @return
	 * @throws Exception
	 * @author Xuzq
	 * @date 2014-3-20 下午05:00:45
	 */
	@RequestMapping("/saveObj")
	@ResponseBody
	public ReturnObject saveOrUpTopic(@RequestBody HashMap<String, Object> bjTopics,String dsId,HttpServletRequest request) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		try {
			DataStore dataStore = singleService.getDataStore(dsId);
			String className = dataStore.getJavaPackageName()+"."+dataStore.getJavaClassName();
		    Class classObj = Class.forName(className);
		    
		    BeanInfo beanInfo = Introspector.getBeanInfo(classObj); // 获取类属性  
	        Object obj = classObj.newInstance(); // 创建 JavaBean 对象  
	  
	        // 给 JavaBean 对象的属性赋值  
	        PropertyDescriptor[] propertyDescriptors =  beanInfo.getPropertyDescriptors();  
	        for (int i = 0; i< propertyDescriptors.length; i++) {  
	            PropertyDescriptor descriptor = propertyDescriptors[i];  
	            String propertyName = descriptor.getName();  
	  
	            if (bjTopics.containsKey(propertyName)) {  
	                // 下面一句可以 try 起来，这样当一个属性赋值失败的时候就不会影响其他属性赋值。  
	            	try {
	            		Object value = bjTopics.get(propertyName);  
	            		Object[] args = new Object[1];  
	            		args[0] = value;  
	            		System.out.println("设置参数 "+propertyName+":"+value);
	            		descriptor.getWriteMethod().invoke(obj, args);  
					} catch (Exception e) {
						e.printStackTrace();
					}
	            }  
	        }  
	        BJTopics bb = (BJTopics)obj;
	        System.out.println(bb.getAuthor()+"  ********   "+bb.getXtName());
		} catch (Exception e) {
			e.printStackTrace();
			returnObject.setMsg(e.getMessage());
		}
		return returnObject;
	}
	
	
	
	
	/**
	 * 导出excel
	 * @param dsId
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/commDCExcel") 
	@ResponseBody
	public String commDCExcel(DataGridReceiveParams dataGParams,String originalSql,String qFlag,String isTotal,String isRep,String dsId,String config,HttpServletRequest request,HttpSession session,HttpServletResponse response) throws Exception{
		response.setContentType("text/html;charset=utf-8");  
		response.setContentType("application/x-msdownload;");
		String newDcName="统计信息.xls";
		String dcName="";
		if(dsId!=null&&!"".equals(dsId)){
			System.out.println(dsId.split(";")[0]);
			DataStore daStore=singleService.getDataStore(dsId.split(";")[0]);
			if(daStore!=null){
				if("true".equals(isRep)){
					dcName=daStore.getPanelTitle();
				}else{
					dcName=daStore.getDsName();
				}
				if(dcName!=null&&!"".equals(dcName)){
					Date date=new Date();
					DateFormat format=new SimpleDateFormat("yyyyMMdd");
					String time=format.format(date);
					newDcName=dcName+"_"+time+".xls";
				}
			}
		}
		response.setHeader("Content-disposition", "attachment; filename="+ new String(newDcName.getBytes("utf-8"), "ISO8859-1"));  
		config = java.net.URLDecoder.decode(config,"UTF-8");
		Map<String,String> map_ =  excelEx(dsId, config, originalSql, qFlag, isTotal, isRep,session);
		String clnSql =   map_.get("clnSql");  //cList
		String finalSql =   map_.get("finalSql"); //dataList
		String cntSql = finalSql.toString().replaceFirst ("\\*", "COUNT(*)");
		System.out.println("=============cntSql:"+cntSql);
		final String DS_ID = "ds_jmjxctj_pz";
		final String SPLIT = "VV_FX_JMJXCTJ";
		if (DS_ID.equalsIgnoreCase(dsId)) {
			StringBuffer finalSqlTmp = new StringBuffer();
			String[] finalSqlSplit = finalSql.split(SPLIT);
			finalSqlTmp.append(finalSqlSplit[0].replace("INPUT_DATE", "FR.INPUT_DATE"));
			finalSqlTmp.append(" ").append(SPLIT).append(" ");
			finalSqlTmp.append(finalSqlSplit[1]);
			StringBuffer cntSqlTmp = new StringBuffer();
			String[] cntSqlTmpSplit = cntSql.split(SPLIT);
			cntSqlTmp.append(cntSqlTmpSplit[0].replace("INPUT_DATE", "FR.INPUT_DATE"));
			cntSqlTmp.append(" ").append(SPLIT).append(" ");
			cntSqlTmp.append(cntSqlTmpSplit[1]);

			finalSql = finalSqlTmp.toString();
			cntSql = cntSqlTmp.toString();
		}
		if("ds_fx_SxManager_MX1".equalsIgnoreCase(dsId)) {
			finalSql = map_.get("finalSql");
			cntSql = map_.get("totalSql");
		}
		int cnt = frameworkService.getCntBySql(cntSql);

		if(cnt/5000 == 0){
			cnt = 1;
		}else if (cnt/5000>0){
			if(cnt%5000==0){
				cnt = cnt/5000;
			}else{
				cnt = cnt/5000+1;
			}
		}
		try{
			HSSFWorkbook wb = new HSSFWorkbook();  //--->创建了一个excel文件
			BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
			for(int k=0;k<cnt;k++){
				List<Map<String,Object>>  cList = frameworkService.execSql(clnSql);
				//
				QueryJson  queryJson = frameworkService.queryRowsBySqlPagination(finalSql, k+1, 5000);
				List<Map<String,Object>> dataList = queryJson.getRows();
				HSSFSheet sheet = wb.createSheet("统计信息"+k);   //--->创建了一个工作簿
				HSSFFont headFont = wb.createFont();
				headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
				headFont.setFontName("Courier New");
				headFont.setFontHeightInPoints((short)25);
				//表头样式
				HSSFCellStyle headStyle = null;
				headStyle = wb.createCellStyle();
				headStyle.setFont(headFont);

				headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

				//主体样式
				HSSFCellStyle bodyStyle = null;
				HSSFFont bodyFont = wb.createFont();
				bodyFont.setFontName("Courier New");
				bodyFont.setFontHeightInPoints((short) 15);

				bodyStyle = wb.createCellStyle();
				bodyStyle.setFont(bodyFont);

				HSSFRow row_title = sheet.createRow(0); 
				row_title.setRowStyle(headStyle);
				row_title.setHeightInPoints(20);
				for(int i=0,size = cList.size();i<size;i++)
				{
					row_title.createCell(i);
					row_title.getCell(i).setCellValue(cList.get(i).get("COLN_NAME").toString());

				}

				for(int i=0,size = dataList.size();i<size;i++){
					HSSFRow row = sheet.createRow(i+1); 
					row.setRowStyle(bodyStyle);
					for(int j=0,size_=cList.size();j<size_;j++){
						String code="";
						String value = "";
						String cln_ = cList.get(j).get("NAME").toString();
						String isMulColn = cList.get(j).get("IS_MULTI_CLNS")==null?"":cList.get(j).get("IS_MULTI_CLNS").toString();   //是否是一对多的字段
						String editType=cList.get(j).get("EDITYPE")==null?"":cList.get(j).get("EDITYPE").toString();
						Map<String, Object> maps=new HashMap<String, Object>();
						value = dataList.get(i).get(cln_)==null?"":dataList.get(i).get(cln_).toString();
						if(!"".equals(editType)&&!"".equals(value)){  
							List<Map<String, Object>> list=MenuController.mapList.get(editType);
							if(list!=null&&list.size()>0){
								for (int l = 0; l < list.size(); l++) {
									maps.put((String) list.get(l).get("ID"), list.get(l).get("NAME"));
								}
								if("T".equals(isMulColn)&&value.split(";").length>0){
									String [] vals=value.split(";");
									value="";
									for (int y = 0; y < vals.length; y++) {
										if(y!=vals.length-1){
											value += (String)maps.get(vals[y])+";";
										}else{
											value += (String)maps.get(vals[y]);
										}
									}
								}else{
									value = (String) maps.get(value);
								}
								
							}
						}
						row.createCell(j);
						if("H_PUBLISH_DATE".equals(cln_) && !"".equals(value)){
							row.getCell(j).setCellValue(value.substring(0, value.indexOf(" ")));
						System.out.println(value.substring(0, value.indexOf(" ")));
						}else{
							row.getCell(j).setCellValue(value);
						}
					}
				}
			}    
			wb.write(bos);
			if (bos != null)  
				bos.close(); 
		}catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private Map<String,String> excelEx(String dsId,String config,String originalSql,String qFlag,String isTotal,String isRep,HttpSession session){
		Map<String,String> map = new HashMap<String, String>(); 
		try {
			String[] dsIds = dsId.split(";");
			DataStore dataStore = frameworkService.getDataStoreById(dsIds[0]);
			Object uid = session.getAttribute(SessionCont.uid);
			if (uid == null || "".equals(uid.toString())) {
				System.out.println("用户未登录 FrameworkController L.318");
			}

			String sql = frameworkService.formatSql(dsIds[0],dataStore.getSqlText(),uid == null?"":uid.toString());
			if (dataStore != null) {
				StringBuffer sqlBuffer = new StringBuffer();
				String[] tmpValue2;
				String date1 = "";  //缓存语句
				String date2 = "";  //缓存语句
				String tmpStr = "";  //缓存语句
				String tmpStr2 = ""; //缓存语句2
				String flagA = ""; //缓存标志
				String tmpName = "";//缓存 字段
				String tmpValue = "";  // 缓存值
				String editype = "";//缓存editype
				config =config.replace("| ", "|+");
				if(config!=null&&config.trim()!=""){
					String[] configS = config.split("\\|\\+");
					StringBuffer whereStr =  new StringBuffer();//缓存条件语句
					for (int i = 0; i < configS.length;i++) {
						if (configS[i] != null && !"".equals(configS[i])) {
							flagA = configS[i].substring(0, 1);
							tmpStr =configS[i].substring(2, configS[i].length());
							//					*     字符串1  ：flag - ClnName - value1 -neq +
							//							eq  等于   		neq 	不等于
							//					 *      alike 以...开头  	likea　	以...结尾    inc包含
							//					 *   数值 间隔2：	 flag - date Num - value1 - value2  +
							//					 *       列表3：     flag - staId - value1;value2 +
							//					 	   时间间隔4:   flag - clnName- date1 - date2 +
							if (flagA.equals("1")) {
								tmpName = tmpStr.substring(0,tmpStr.indexOf("-"));
								tmpStr2 = tmpStr.substring(tmpStr.lastIndexOf("-")+1,tmpStr.length());
								tmpStr = tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.lastIndexOf("-")).trim();
								if("".equals(tmpStr)){
									continue;
								}
								//获取input框传入的参数
								String parm=tmpStr.toString().toUpperCase();
								String [] parms=parm.split(";");
								//遍历参数       对出版社简sql条件进行添加
								for(String p:parms){
									if("eq".equals(tmpStr2)){
										if(p.matches("^[^a-zA-Z]*$")){
											sqlBuffer.append(" AND nvl("+tmpName+",0) = '"+p+"' ");
										}else {
											sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('"+p+"') ");
										}

										//	sqlBuffer.append(" AND (("+tmpName+"='"+p+"') OR (upper(getch2spell(Nvl("+tmpName+",' ')))= getch2spell('"+p+"')))  ");
									}else if ("neq".equals(tmpStr2)) {
										if(p.matches("^[^a-zA-Z]*$")){
											sqlBuffer.append(" AND ("+tmpName+" not in ('"+p+"'))  ");
										}else {
											sqlBuffer.append(" AND  (upper(getch2spell(Nvl("+tmpName+",' ')))  not in getch2spell('"+p+"')) ");
										}
										//sqlBuffer.append(" AND (("+tmpName+" not in ('"+p+"')) AND  upper((getch2spell(Nvl("+tmpName+",' ')))  not in getch2spell('"+p+"')))");
									}else if("alike".equals(tmpStr2)) {
										if(p.matches("^[^a-zA-Z]*$")){
											sqlBuffer.append(" AND "+tmpName+" like '"+p+"%' ");
										}else {
											sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('"+p+"%')  ");
										}
										//	sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('"+p+"%') ");
									}else if ("likea".equals(tmpStr2)) {
										if(p.matches("^[^a-zA-Z]*$")){
											sqlBuffer.append(" AND "+tmpName+" like '%"+p+"'");
										}else {
											sqlBuffer.append("  AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('%"+p+"')  ");
										}

										//sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('%"+p+"') ");
									}else if ("inc".equals(tmpStr2)) {
										//判断传入的参数不是英文
										if(p.matches("^[^a-zA-Z]*$")){
											sqlBuffer.append(" AND "+tmpName+" like '%"+p+"%' ");
										}else {
											sqlBuffer.append(" AND upper(getch2spell(Nvl("+tmpName+",' '))) like getch2spell('%"+p+"%') ");
										}
									}
								}
							}else if (flagA.equals("2")) {
								//							 *    间隔2：	   flag - clnName - Num - num2  +
								tmpName = tmpStr.substring(0,tmpStr.indexOf("-"));
								if(tmpStr.lastIndexOf("-") > tmpStr.length()+1){
									tmpStr2 = tmpStr.substring(tmpStr.lastIndexOf("-")+1,tmpStr.length());
									sqlBuffer.append(" AND "+tmpName+" <= "+tmpStr2+" ");
								}
								tmpStr = tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.lastIndexOf("-"));
								if(!"".equals(tmpStr)){
									sqlBuffer.append(" AND "+tmpName+" >= "+tmpStr+" ");
								}
							}else if (flagA.equals("3")) {   //3-STOCK_ID-GOM1K00000|+        3-PRINT_MAN-22378EADC22087536F54752CD5FD1CE6|+
								//							flag - staId - value1;value2 +       
								tmpName = tmpStr.substring(0,tmpStr.indexOf("-"));
								tmpStr =  tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.length());
								if("".equals(tmpStr)){
									continue;
								}
								tmpValue2 = tmpStr.split(";");
								tmpStr = "";
								for(int k = 0; k < tmpValue2.length; k ++){
									tmpStr += "'"+tmpValue2[k]+"'";
									if (k < tmpValue2.length - 1) {
										tmpStr += ",";
									}
								}
								sqlBuffer.append(" AND "+tmpName+" in ("+tmpStr+")");
							}else if (flagA.equals("4")) {
//								时间间隔4:   flag - clnName- date1 - date2 +
								//							 input_date >  to_date('2014-5-12 00:00:00','yyyy-mm-dd hh24:mi:ss')
								//							SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
								SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
								tmpName = tmpStr.substring(0,tmpStr.indexOf("-"));
								String tmpStr3 = tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.lastIndexOf("-"));   //第一个时间框内的值
								String tmpStr21 = tmpStr.substring(tmpStr.lastIndexOf("-")+1,tmpStr.length());  //第二个时间框内的值
								date1 = tmpStr3;
								date2 = tmpStr21;
								if (!"".equals(tmpStr3)&&!"".equals(tmpStr21)&&tmpStr3.equals(tmpStr21)) {  //两个框内都有值,，并且两个值相等
									String jqDate=df.format(new Date(Long.parseLong(tmpStr3)));
									sqlBuffer.append(" AND to_char("+ tmpName+" ,'yyyy-MM-dd')  = '"+jqDate+"'");
								}else{
									if(!"".equals(tmpStr3)){
										sqlBuffer.append(" AND to_char("+ tmpName +",'yyyy-MM-dd') >= '"+df.format(new Date(Long.parseLong(tmpStr3)))+"'");
									}
									if(!"".equals(tmpStr21)){
										sqlBuffer.append(" AND to_char("+ tmpName +",'yyyy-MM-dd') <= '"+df.format(new Date(Long.parseLong(tmpStr21)))+"'");
									}
								}
							}else if (flagA.equals("5")) {
								//5 flag - ClnName - editype - value1 -neq |+
								if("".equals(tmpStr)){
									continue;
								}
								String colnName=tmpStr.substring(0,tmpStr.indexOf("-"));      //列名
								String operatorFlag=tmpStr.substring(tmpStr.lastIndexOf("-")+1,tmpStr.length());  //关系运算符
								tmpStr =tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.lastIndexOf("-")); //dzId-value    

								//								

								String dzId = tmpStr.substring(0,tmpStr.indexOf("-"));   //编码对照信息的dzId
								String valueStr= tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.length());   //输入的查询条件的字符串的
								String[] valArr1=valueStr.split(";");  //前台输入的谐音数组 NAME = CL;JK;KL;
								//								List<String> vals=new ArrayList<String>();  //谐音数组过滤后过控制的集合的值
								//								for (int j = 0; j < valArr1.length; j++) {
								//									if(valArr1[j]!=null&&valArr1[j]!=""){
								//										vals.add(valArr1[j]);
								//									}
								//								}
								String sqlForText ="select sql_text,show_pk,show_name from sys_dz_source c where c.dz_id ='"+dzId+"'";
								SysDzSource dzSource =(SysDzSource) frameworkService.sqlForList(sqlForText);
								String showName = dzSource.getShowName();
								String showPk=dzSource.getShowPk();
								String sqlText = dzSource.getSqlText();

								//								StringBuffer configSql = new StringBuffer();
								//								configSql.append(" AND ");

								String sqlConfig =" AND";
								for(int n=0;n<valArr1.length;n++){
									String p = valArr1[n];
									if("eq".equals(operatorFlag)){
										if(p.matches("^[a-zA-Z]*$")){
											sqlConfig +="  upper(getch2spell(Nvl("+showName+",' ')))= getch2spell(Nvl('"+p.trim().toUpperCase()+"',''))  ";
										}else {
											sqlConfig +=" ("+showName+"='"+p+"')";
										}
									}else if ("neq".equals(operatorFlag)) {
										sqlConfig +="("+showName+" not in ('"+p+"')) ";
									}else if ("alike".equals(operatorFlag)) {
										if(p.matches("^[a-zA-Z]*$")){
											sqlConfig +=" upper(getch2spell(Nvl("+showName+",' '))) like getch2spell('"+p.trim().toUpperCase()+"%') ";
										}else {
											sqlConfig +=" nvl("+showName+",' ') like '"+p+"%'";
										}
									}else if ("likea".equals(operatorFlag)) {
										if(p.matches("^[a-zA-Z]*$")){
											sqlConfig +="  upper(getch2spell(Nvl("+showName+",' '))) like getch2spell('%"+p.trim().toUpperCase()+"')";
										}else {
											sqlConfig +=" Nvl("+showName+",' ') like '%"+p+"'";
										}
									}else if ("inc".equals(operatorFlag)) {
										if(p.matches("^[a-zA-Z]*$")){
											sqlConfig +=" upper(getch2spell(Nvl("+showName+",' '))) like getch2spell('%"+p.trim().toUpperCase()+"%') ";
										}else {
											sqlConfig +=" Nvl("+showName+",' ') like '%"+p+"%'";
										}
									}
									if (n<valArr1.length-1) {
										sqlConfig = sqlConfig +" OR";
									}
									//拼接条件
									//									configSql.append(getSql(vals,showName,sqlConfig));
								}
								//得到前台输入的条件的编码的集合
								//								String tmpSql = " select  "+showPk +" from ("+ sqlText+") A where 1=1 "+configSql;
								String tmpSql = " select  "+showPk +" from ("+ sqlText+") A where 1=1 "+sqlConfig;
								List<Map<String,String>> idList = frameworkService.execSql(tmpSql);

								StringBuffer likestr = new StringBuffer();
								if (idList != null && !idList.isEmpty()) {
									for (int j = 0; j < idList.size(); j++) {
										likestr.append( colnName + " like '%"+idList.get(j).get(dzSource.getShowPk())+"%'");
										if(j<(idList.size()-1)){
											likestr.append(" or ");
										}
									}                                                                                                                                                          
									sqlBuffer.append(" AND ("+ likestr+") ");
								}else {
									sqlBuffer.append(" AND (0=1) ");
								}
							}else if (flagA.equals("6")) {	//一对多根据ID查
								//							flag - clnName - dsid - value1;value2 +
								//根据dsid 和 name 查找对应的表   及对应的字段、
								String clnName = tmpStr.substring(0, tmpStr.indexOf("-"));
								tmpStr = tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.length());
								String dsid = tmpStr.substring(0,tmpStr.indexOf("-"));
								//查找出包含的所有的字段
								//只查询mul的四个字段  
								//MULTI_CLNS_TABLE,MULTI_CLNS_FK,MULTI_CLNS_VALUE,MULTI_DZ_DS_ID
								SysColumns tmpOnly4P = this.frameworkService.queryColumnsMul(dsid,clnName);
								//select distinct sin_id where mul_id in (ids);
								//								sql语句 本字段   包含在这里面
								String[] idsArr = tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.length()).split(";");
								StringBuffer tmpIds = new StringBuffer();
								//								V1.0.1
								//								for(int k = 0; k < idsArr.length; k ++){
								//									tmpIds.append("'"+idsArr[k]+"'");
								//									if (k < idsArr.length - 1) {
								//										tmpIds.append(",");
								//									}
								//								}
								//								v2.0
								for(int k = 0; k < idsArr.length; k ++){
									tmpIds.append(clnName + " LIKE '%"+idsArr[k]+"%' ");
									if (k < idsArr.length - 1) {
										tmpIds.append(" OR ");
									}
								}

								//			" AND SIN_ID IN (select distinct sin_id where mul_id in (ids))
								tmpStr = " select distinct "+ tmpOnly4P.getMultiClnsFk() 
								+" from " + tmpOnly4P.getMultiClnsTable()
								+" where " + tmpOnly4P.getMultiClnsDValue()+" in ("
								+tmpIds+")";
								//								sqlBuffer.append(" AND "+clnName+" in ("+tmpStr+")"); //v1.0.1
								sqlBuffer.append(" AND ("+tmpIds+")"); //v2.0.0
							}
							//一对多的模糊查询(flag - clnName - dsid - value1;value2 -neq +)
							else if (flagA.equals("7")) {	
								String clnName = tmpStr.substring(0, tmpStr.indexOf("-")); //列名
								String operatorFlag=tmpStr.substring(tmpStr.lastIndexOf("-")+1,tmpStr.length());  //关系运算符
								tmpStr =tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.lastIndexOf("-")); //dzId-value
								String dzId = tmpStr.substring(0,tmpStr.indexOf("-"));   //编码对照信息的dzId
								String valueStr= tmpStr.substring(tmpStr.indexOf("-")+1,tmpStr.length());   //输入查询条件字符串
								String[] valArr1=valueStr.split(";");  //字符串分割的谐音数组
								List<String> vals=new ArrayList<String>();  //谐音数组过滤后过控制的集合的值
								for (int j = 0; j < valArr1.length; j++) {
									if(valArr1[j]!=null&&valArr1[j]!=""){
										vals.add(valArr1[j]);
									}
								}
								//根据dsId，和列名查询该列一对多的的配置信息
								SysColumns mulObj = this.frameworkService.queryColumnsMul(dsId,clnName);
								SysDzSource dzSource = this.frameworkService.loadDzSource(dzId);
								if (dzSource == null ) {
									throw new RuntimeException("找不到对照信息["+mulObj.getEditypeQr()+"]用于条件查询");
								}
								String showName = dzSource.getShowName();
								String showPk=dzSource.getShowPk();
								StringBuffer sqlText = new StringBuffer(dzSource.getSqlText());

								String sqlConfig =" AND";
								for(int n=0;n<valArr1.length;n++){
									String p = valArr1[n];
									if("eq".equals(operatorFlag)){
										if(p.matches("^[a-zA-Z]*$")){
											sqlConfig +="  upper(getch2spell(Nvl("+showName+",' ')))= getch2spell(Nvl('"+p.trim().toUpperCase()+"',''))  ";
										}else {
											sqlConfig +=" ("+showName+"='"+p+"')";
										}
									}else if ("neq".equals(operatorFlag)) {
										sqlConfig +="("+showName+" not in ('"+p+"')) ";
									}else if ("alike".equals(operatorFlag)) {
										if(p.matches("^[a-zA-Z]*$")){
											sqlConfig +=" upper(getch2spell(Nvl("+showName+",' '))) like getch2spell('"+p.trim().toUpperCase()+"%') ";
										}else {
											sqlConfig +=" nvl("+showName+",' ') like '"+p+"%'";
										}
									}else if ("likea".equals(operatorFlag)) {
										if(p.matches("^[a-zA-Z]*$")){
											sqlConfig +="  upper(getch2spell(Nvl("+showName+",' '))) like getch2spell('%"+p.trim().toUpperCase()+"')";
										}else {
											sqlConfig +=" Nvl("+showName+",' ') like '%"+p+"'";
										}
									}else if ("inc".equals(operatorFlag)) {
										if(p.matches("^[a-zA-Z]*$")){
											sqlConfig +=" upper(getch2spell(Nvl("+showName+",' '))) like getch2spell('%"+p.trim().toUpperCase()+"%') ";
										}else {
											sqlConfig +=" Nvl("+showName+",' ') like '%"+p+"%'";
										}
									}
									if (n<valArr1.length-1) {
										sqlConfig = sqlConfig +" OR";
									}
								}
								String tmpSql = " select  "+ showPk +" from ("+ sqlText+") A where 1=1 "+sqlConfig;
								//获取编码的集合
								List<Map<String,String>> idList = frameworkService.execSql(tmpSql);
								StringBuffer likestr=new StringBuffer();
								if (idList != null && !idList.isEmpty()) {
									for (int j = 0; j < idList.size(); j++) {
										likestr.append( clnName + " like '%"+idList.get(j).get(showPk)+"%'");
										if(j<(idList.size()-1)){
											likestr.append(" or ");
										}
									}                                                                                                                                                          
									sqlBuffer.append(" AND ("+ likestr+") ");
								}else {
									sqlBuffer.append(" AND (0=1) ");
								}
							}else{
								throw new RuntimeException("查询条件传入有误,没有按照相关规则,请联系开发调试");
							}
						}
					}
				}

				StringBuffer finalSql= new StringBuffer("select * from ("+sql+") QUERYTMP where 1 = 1  ");
				//拼接页面的查询条件sql(排除报表，所有的报表用AINIT'='AINIT 替换查询条件)
				if(!"true".equals(isRep)){
					finalSql.append(sqlBuffer);
				}
				//拼接数据权限sql
				String conditionSql= frameworkService.queryConditionSql(dsId,uid.toString());
				
				/***
				 * 如果sql语句总拼接了'RIGHTSQL'='RIGHTSQL' 那么此时就把权限对应的sql语句拼接到此位置
				 */
				String rightParam="'RIGHTSQL'='RIGHTSQL'";
				if(finalSql.toString().indexOf(rightParam)>0&&conditionSql!=null&&!"".equals(conditionSql.trim())){  
					//把sqlBuffer的and 去掉
					conditionSql=conditionSql.toString().replaceFirst("and", " ");
					finalSql=new StringBuffer(finalSql.toString().replace(rightParam, conditionSql));
				}
				else{
					if(conditionSql!=null){
						finalSql.append(conditionSql);
					}
				}
				
				//sql中替换掉$dsid
				finalSql.toString().replace("$dsid", dsIds[0]);
				// 如果sql语句中包含AINIT' = 'AINIT 那么该字符串用查询条件替换掉sqlBuffer
				String chanParam="'AINIT'='AINIT'";
				if(finalSql.toString().indexOf(chanParam)>0&&!sqlBuffer.toString().trim().equals("")){  
					//把sqlBuffer的and 去掉
					sqlBuffer=new StringBuffer(sqlBuffer.toString().replaceFirst("AND"," "));
					finalSql=new StringBuffer(finalSql.toString().replace(chanParam, sqlBuffer));
				}

				String QcDataParam = "'STOCKDATE'='STOCKDATE'";
				if (finalSql.toString().indexOf(QcDataParam) > 0) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String qcDate = "";
					if ((!"".equals(date1)) && (!"".equals(date2))) {
						String jqDate = df.format(new Date(Long.parseLong(date1)));
						String jqDate1 = df.format(new Date(Long.parseLong(date2)));
						qcDate = " to_char(IMPORT_DATEM, 'yyyy-MM-dd') >= '" + jqDate + "' and  to_char(IMPORT_DATEM, 'yyyy-MM-dd') <= '" + jqDate1 + "'";
					} else if (!"".equals(date1)) {
						String jqDate = df.format(new Date(Long.parseLong(date1)));
						qcDate = " to_char(IMPORT_DATEM, 'yyyy-MM-dd') >= '" + jqDate + "'";
					} else if(!"".equals(date2)) {
						String jqDate1 = df.format(new Date(Long.parseLong(date2)));
						qcDate = " and  to_char(IMPORT_DATEM, 'yyyy-MM-dd') <= '" + jqDate1 + "'";
					}
					if (qcDate == "") {
						qcDate = "1=1";
					} else {
						finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam, qcDate));
					}
				}
				String QcDataParam2 = "QCDATE=QCDATE";
				if (finalSql.toString().indexOf(QcDataParam2) > 0) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String qcDate = "";
					if ((!"".equals(date1)) && (!"".equals(date2))) {
						String jqDate = df.format(new Date(Long.parseLong(date1)));
						String jqDate1 = df.format(new Date(Long.parseLong(date2)));
						qcDate = jqDate + '#' + jqDate1;
					}
					finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam2, qcDate));
				}

				String QcDataParam3 = "'XSINFO'='XSINFO'";
				if (finalSql.toString().indexOf(QcDataParam3) > 0 && !sqlBuffer.toString().trim().equals("")) {
					//把sqlBuffer的and 去掉
					sqlBuffer = new StringBuffer(sqlBuffer.toString().replaceFirst("AND", " "));
					if (sqlBuffer.indexOf("STOCK_DATE") != -1 && sqlBuffer.indexOf("CLIENT_ID") != -1) {
						sqlBuffer = new StringBuffer(sqlBuffer.toString().substring(0, (sqlBuffer.indexOf("STOCK_DATE") - 12)));
					}
					if (sqlBuffer.indexOf("STOCK_DATE") != -1 && sqlBuffer.indexOf("CLIENT_ID") == -1) {
						if(sqlBuffer.indexOf("H_NAME") != -1) {
							sqlBuffer = new StringBuffer(sqlBuffer.toString().substring(0, (sqlBuffer.indexOf("STOCK_DATE") - 12)));
							finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam3, sqlBuffer));
						} else {
							sqlBuffer = new StringBuffer(sqlBuffer.toString().substring(0, (sqlBuffer.indexOf("STOCK_DATE") - 11)));
							finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam3, "1=1"+sqlBuffer));
						}
					}
					finalSql = new StringBuffer(finalSql.toString().replace(QcDataParam3, sqlBuffer));
					System.out.println("======================#FrameworkController 750  查询生成的SQL语句" + finalSql);
				}

				if ("ds_fx_SxManager_MX1".equalsIgnoreCase(dsId)) {
					finalSql = new StringBuffer(finalSql.toString().replace("IMPORT_DATEM", "IMPORT_DATE"));
					int first = finalSql.indexOf("IMPORT_DATE");
					int leg = "IMPORT_DATE".length();
					finalSql = finalSql.replace(first, first+leg, "STOCK_DATE");
					first = finalSql.indexOf("IMPORT_DATE");
					finalSql = finalSql.replace(first, first+leg, "STOCK_DATE");

					String maxDate = "'MAXDATE'='MAXDATE'";
					SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
					String max = format.format(new Date(Long.parseLong(date2)));
					finalSql = new StringBuffer(finalSql.toString().replace(maxDate, "to_char(IMPORT_DATE, 'yyyy-MM')='"+max+"'"));

					String qcDate = "'QCDATE'='QCDATE'";
					SimpleDateFormat qcFmt = new SimpleDateFormat("yyyy-MM");
					String qc = qcFmt.format(new Date(Long.parseLong(date1)));
					finalSql = new StringBuffer(finalSql.toString().replace(qcDate, "to_char(DATA_MONTH, 'yyyy-MM')='"+qc+"'"));

					String[] tmp = finalSql.toString().split("--WHERE--");
					finalSql = new StringBuffer().append(tmp[0]).append(tmp[1].replace("CLIENT_ID", "VCP.CLIENT_ID")).append(tmp[2]);


					StringBuffer totalSql = new StringBuffer();
					totalSql.append("select count(*) ");
					totalSql.append(finalSql.toString().split("--TOTAL--")[1]);

					finalSql = new StringBuffer(finalSql.substring(finalSql.indexOf("select t2"), finalSql.lastIndexOf("t2")+2));
					map.put("totalSql", totalSql.toString());
				}

				String clnSql="SELECT DS_ID,IS_MULTI_CLNS, NAME,Editype,COLN_NAME, ORDERNUM FROM SYS_COLUMNS WHERE DS_ID = '"+dsId+"' AND (HIDDEN != 'T' OR HIDDEN IS NULL) AND JAVA_PROPERTY_RECORDED IS NOT NULL ORDER BY ORDERNUM";

				map.put("clnSql", clnSql);
				map.put("finalSql", finalSql.toString());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	/**
	 * 导出数据（出入dsId和已有的数据List） 
	 * @param dsId
	 * @param rowsList
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 * @author wyy
	 */
	@RequestMapping("/modelDCExcel") 
	@ResponseBody
	public ReturnObject modelDCExcel(String dsId,@RequestBody List<Map<String,Object>> rowsList,HttpServletRequest request,HttpSession session) throws Exception{
		ReturnObject returnObject = new ReturnObject();
		DataStore dataStore = new DataStore();
		List<Map<String, Object>> columns = new ArrayList<Map<String, Object>>();
		String[] dsIds = dsId.split(";");
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if(uid == null || "".equals(uid.toString())){
				System.out.println("用户未登录..FrameworkController L.506");
			}
			dataStore = singleService.getDataStore(dsIds[0]);
			String title = dataStore.getPanelTitle();
			//1.传入保存文件的位置和名称
//			String fileUrl ="D://"+title+DateTimeStr.getDateTimeNo()+".xls";
 
			String fileStr = this.getClass().getResource("/").getFile().toString()+"..\\..\\exportFile\\"+DateTimeStr.formatDateStrLong()+".xls";
			String fileUrlStr = request.getContextPath()+"/exportFile/"+DateTimeStr.formatDateStrLong()+".xls"; //返回前台的js访问路径
 
			//2.得到在excel中显示的名称（columnName）
			//3.sql中的列名（name）
			//列表界面
			String sql1 = "SELECT * FROM BS_EXPORT_COLUMN WHERE DS_ID ='"+dsIds[0]+"' ORDER BY ORDER_NUM";
			String sql2 = "SELECT DS_ID,NAME,COLN_NAME,ORDERNUM FROM SYS_COLUMNS WHERE DS_ID ='"+dsIds[0]+"' AND (HIDDEN !='T' OR HIDDEN IS NULL) AND (IS_PARENT_GROUP_QR !='T' OR IS_PARENT_GROUP_QR IS NULL)";
			columns = singleService.queryRowBySql(sql1);
			if (columns == null || columns.isEmpty()) {
				columns = singleService.queryRowBySql(sql2);
			}
			String[] coluName = new String[columns.size()];
			String[] names = new String[columns.size()];
			for (int i = 0; i < columns.size(); i++) {
				coluName[i] = (String) columns.get(i).get("COLN_NAME");
				names[i] = (String) columns.get(i).get("NAME");
			}
			List<Map<String, String>> rowsAll = new ArrayList<Map<String, String>>();
			for (int j = 0; j < rowsList.size(); j++) {
				Map<String, String> mapTmp = new HashMap<String, String>();
				Object[] rowsTmp = rowsList.get(j).keySet().toArray();
				for (int i = 0; i < rowsTmp.length; i++) {
					mapTmp.put(rowsTmp[i].toString(), rowsList.get(j).get(rowsTmp[i]) == null ? "" : rowsList.get(j).get(rowsTmp[i]).toString());
				}
				rowsAll.add(mapTmp);
			}
			returnObject.setUrl(fileUrlStr);
			returnObject.setInfo(title);
			String resultAn= singleService.dcExcel(title, fileStr, coluName, names, rowsAll);
			returnObject.setMsg(resultAn);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnObject;
	}
	
	//连接到导入界面
	@RequestMapping("improtjsp")
	public String returnimprotjsp(){
		return "model/importExcel/imprortExcel";
	}
	//把导入的信息处理后返回到界面
	@SuppressWarnings("unchecked")
	@RequestMapping("/improtRetunInfo")
	@ResponseBody
	public  QueryJson getImprotInfo(SingleParam sp, HttpServletRequest request ) throws IOException{
		String keys = request.getParameter("keys");
		String flg = keys.split("/")[0];
		String dsid = keys.split("/")[1];
		String kvs = keys.split("/")[2];
		sp.setUrl(sp.getFile().getOriginalFilename());
		sp.setInputStram(sp.getFile().getInputStream());
		QueryJson queryJson=new QueryJson();
		queryJson.setJson(singleService.getReturnImproInfo(flg,dsid,kvs,sp));
		return   queryJson;
	}

	//把导入的信息处理后返回到界面
	@SuppressWarnings("unchecked")
	@RequestMapping("/improtRetunInfoZT")
	@ResponseBody
	public  QueryJson improtRetunInfoZT(SingleParam sp, HttpServletRequest request ) throws IOException{
		String keys = request.getParameter("keys");
		String flg = keys.split("/")[0];
		String dsid = keys.split("/")[1];
		String kvs = keys.split("/")[2];
		sp.setUrl(sp.getFile().getOriginalFilename());
		sp.setInputStram(sp.getFile().getInputStream());
		QueryJson queryJson=new QueryJson();
		queryJson.setJson(singleService.getReturnImproInfoZT(flg,dsid,kvs,sp));
		return   queryJson;
	}

	//把导入的信息处理后返回到界面
	@SuppressWarnings("unchecked")
	@RequestMapping("/improtRetunInfoCYXH")
	@ResponseBody
	public  QueryJson improtRetunInfoCYXH(SingleParam sp, HttpServletRequest request ) throws IOException{
		String keys = request.getParameter("keys");
		String flg = keys.split("/")[0];
		String dsid = keys.split("/")[1];
		String kvs = keys.split("/")[2];
		sp.setUrl(sp.getFile().getOriginalFilename());
		sp.setInputStram(sp.getFile().getInputStream());
		QueryJson queryJson=new QueryJson();
		queryJson.setJson(singleService.getReturnImproInfoCYXH(flg,dsid,kvs,sp));
		return   queryJson;
	}
	
	//把导入的信息处理后返回到界面
	@SuppressWarnings("unchecked")
	@RequestMapping("/improtRetunInfoCw")
	@ResponseBody
	public  QueryJson getImprotInfoCw(SingleParam sp, HttpServletRequest request ) throws IOException{
		String keys = request.getParameter("keys");
		String flg = keys.split("/")[0];
		String dsid = keys.split("/")[1];
		String kvs = keys.split("/")[2];
		sp.setUrl(sp.getFile().getOriginalFilename());
		sp.setInputStram(sp.getFile().getInputStream());
		QueryJson queryJson=new QueryJson();
		queryJson.setJson(singleService.getReturnImproInfoCw(flg,dsid,kvs,sp));
		return   queryJson;
	}
	
	//销售费用中把导入的信息处理后返回到界面												
		@RequestMapping("/improtRetunInfoFee")
		@ResponseBody
		public  QueryJson getImprotInfoFee(SingleParam sp, HttpServletRequest request ) throws IOException{
			String keys = request.getParameter("keys");
			String flg = keys.split("/")[0];
			String dsid = keys.split("/")[1];
			String kvs = keys.split("/")[2];
			sp.setUrl(sp.getFile().getOriginalFilename());
			sp.setInputStram(sp.getFile().getInputStream());
			QueryJson queryJson=new QueryJson();
			queryJson.setJson(singleService.getReturnImproInfoFee(flg,dsid,kvs,sp));
			return   queryJson;
		}
	/**************************************
	 * js 上传excel后,分析excel,并将数据转换成json,插入到服务器
	 * 2015年11月26日15:57:26 刘振涛
	 * @param sp
	 * @param request
	 * @return
	 * @throws IOException
	 **************************************/
	@RequestMapping("/importExcel")
	@ResponseBody
	public  QueryJson ImportExcel(SingleParam sp, HttpServletRequest request,HttpSession session) throws IOException{
		String keys = request.getParameter("keys");
		String flg = keys.split("/")[0];
		String dsid = keys.split("/")[1];
		String uid=session.getAttribute(SessionCont.uid).toString();
		sp.setUrl(sp.getFile().getOriginalFilename());
		sp.setInputStram(sp.getFile().getInputStream());
		QueryJson queryJson=new QueryJson();
		queryJson.setJson(singleService.ImpExcelToDbAndProc(sp, dsid,uid));
		return   queryJson;
	}
	
  //把导入的信息处理后返回到界面
    @RequestMapping("/improtRetun")
    @ResponseBody
	public QueryJson getImprot(SingleParam sp) throws IOException{
    	QueryJson queryJson=new QueryJson();
    	sp.setUrl(sp.getFile().getOriginalFilename());
    	sp.setInputStram(sp.getFile().getInputStream());
    	queryJson.setRows(singleService.getReturnImpro(sp));
    	return   queryJson;
	}
  //把导入的信息处理后返回到界面 （客户）
    @RequestMapping("/improtRetunKH")
    @ResponseBody
	public QueryJson improtRetunKH(SingleParam sp) throws IOException{
    	QueryJson queryJson=new QueryJson();
    	sp.setUrl(sp.getFile().getOriginalFilename());
    	sp.setInputStram(sp.getFile().getInputStream());
    	queryJson.setRows(singleService.getReturnImproKH(sp));
    	return   queryJson;
	}
	/**
	 * 导入
	 * @param flag
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/pageToImport") 
	public String pageToImport(String dsid,String kvs,String flag,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dsid", dsid);
			map.put("kvs", kvs);
			map.put("flag", flag);
			session.setAttribute("data",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "model/importExcel/imprortExcel";
	}
	/**
	 * 财务导入
	 * @param flag
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/CwpageToImport") 
	public String CwpageToImport(String dsid,String kvs,String flag,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dsid", dsid);
			map.put("flag", flag);
			session.setAttribute("data",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "model/cwImportExcel/imprortExcel";
	}
	
	/**
	 * 活动费用导入加载
	 * @param flag
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/FeepageToImport" ) 
	public String FeepageToImport(String dsid,String kvs,String flag,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dsid", dsid);
			map.put("flag", flag);
			session.setAttribute("data",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "model/feeImportExcel/imprortExcel";
	}
	/**
	 * 双击根据商品的H_isbn查找相关数据
	 * @Title: mataOrderInfo
	 * @author : FuXiangYi  
	 * @Description: 获取可供配置的商品信息
	 * @param request
	 * @param sp
	 * @return    
	 * @return String 
	 * @date 2014-10-31 下午02:39:00
	 */
	@RequestMapping("mataOrder")
	@ResponseBody
	public List<Map<String, Object>> mataOrderInfo(HttpServletRequest request,SingleParam sp){
		   List<Map<String , Object>> list=singleService.getOrerInfo(sp);
		return list;
	}
	/**
	 * 根据客户名称来查找相关数据
	 * @param request
	 * @param sp
	 * @return
	 */
	@RequestMapping("mataOrderKH")
	@ResponseBody
	public List<Map<String, Object>> mataOrderKH(HttpServletRequest request,SingleParam sp){
		   List<Map<String , Object>> list=singleService.getOrderKHInfo(sp);
		return list;
	}
	/**
	 * 根据客户Id查询客户信息
	 * @param cId
	 * @param request
	 * @return
	 */
	@RequestMapping("clientById")
	@ResponseBody
	public List<Map<String, Object>> clientById(String cId,HttpServletRequest request){
		   List<Map<String , Object>> list=singleService.getClientById(cId);
		return list;
	}
	/**
	 * 删除商品临时表中的导入数据
	 * @param sp
	 * @return
	 */
	@RequestMapping("delsmataOrder")
	@ResponseBody
	public boolean delsMataOrder(SingleParam sp){
		boolean bool=singleService.getDelMateOrder(sp);
		return bool;
	}
	/**
	 * 删除商品临时表中的导入数据
	 * @param sp
	 * @return
	 */
	@RequestMapping("delsmataOrder2")
	@ResponseBody
	public boolean delsMataOrder2(SingleParam sp){
		boolean bool=singleService.getDelMateOrder2(sp);
		return bool;
	}
	/**
	 * 删除客户临时表中的导入数据
	 * @param sp
	 * @return
	 */
	@RequestMapping("delsmataOrderKH")
	@ResponseBody
	public boolean delsmataOrderKH(SingleParam sp){
		boolean bool=singleService.getDelMateOrder(sp);
		return bool;
	}
	/**
	 * 
	 * @Title: getPrebutten
	 * @author : FuXiangYi  
	 * @Description: 
	 * @param request
	 * @param butnId  butn id
	 * @return    
	 * @return List<Map<String,Object>> 
	 * @date 2014-11-20 上午09:55:22
	 */
	@RequestMapping("/prebuten")
	@ResponseBody
	public ModelReturnObj getPrebutten(HttpServletRequest request,String butnId,HttpSession session ,String dsId){
		Object uid = session.getAttribute(SessionCont.uid);
		String[] colIds = dsId.split(";");
		ModelReturnObj modelReturnObj = new ModelReturnObj();
		if(butnId!= null &&  !butnId.equals("")){
			String[] butnB = butnId.split(";");
			List butnList = new ArrayList(); 
			for(int w = 0; w < butnB.length; w++){
				List listTmp;
				try {
					listTmp = this.singleService.butnListRight(butnB[w],colIds[w], uid.toString(),modelReturnObj.getFlag());
					butnList.add(listTmp !=null?listTmp:new ArrayList());
					System.out.println(listTmp);
				} catch (Exception e) {
					
					e.printStackTrace();
				}
			}
		//	pTypeList=this.singleService.printTypeList(colIds[0]);
			modelReturnObj.setPreButnList(butnList);
		}
		return modelReturnObj;
	}
	@RequestMapping("/dbclickFunc")
	@ResponseBody
	public String dbclickFunc(String dsId,String pkVal,HttpServletRequest request,HttpSession session) throws Exception{
		String flagStr = "";
		try {
			Object uid = session.getAttribute(SessionCont.uid);
			if(uid == null || "".equals(uid.toString())){
				System.out.println("用户未登录..FrameworkController L.506");
			}
			flagStr = this.singleService.dbclickRight(dsId, pkVal, uid.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flagStr;
	}
	
	@RequestMapping("dow")
	@ResponseBody
	public String downloadExecle(String fileName,HttpServletRequest request ,HttpServletResponse response) throws Exception{

		response.setContentType("text/html;charset=utf-8");  
		request.setCharacterEncoding("UTF-8");  
		java.io.BufferedInputStream bis = null;  
		java.io.BufferedOutputStream bos = null;  
		//获取文件的位置
		String ctxPath = request.getSession().getServletContext().getRealPath(  
		"/")  
		+ "model\\importTemplate\\";  
		String downLoadPath = ctxPath + fileName;  
		System.out.println(downLoadPath);  
		try {  
			long fileLength = new File(downLoadPath).length();  
			response.setContentType("application/x-msdownload;");  
			response.setHeader("Content-disposition", "attachment; filename="  
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
			response.setHeader("Content-Length", String.valueOf(fileLength));  
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
			bos = new BufferedOutputStream(response.getOutputStream());  

			byte[] buff = new byte[2048];  
			int bytesRead;  
			//遍历出文件流 并输出
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
				bos.write(buff, 0, bytesRead);  
			}  
		} catch (Exception e) {  
			e.printStackTrace();  
		} finally {  
			if (bis != null)  
				bis.close();  
			if (bos != null)  
				bos.close();  
		}  
		return null;  
	}
	
	
	
	@RequestMapping("dowCw")
	@ResponseBody
	public String downloadExecleCw(String fileName,HttpServletRequest request ,HttpServletResponse response) throws Exception{

		response.setContentType("text/html;charset=utf-8");  
		request.setCharacterEncoding("UTF-8");  
		java.io.BufferedInputStream bis = null;  
		java.io.BufferedOutputStream bos = null;  
		//获取文件的位置
		String ctxPath = request.getSession().getServletContext().getRealPath(  
		"/")  
		+ "model\\importTemplateFee\\";  
		String downLoadPath = ctxPath + fileName;  
		System.out.println("downLoadPath="+downLoadPath);  
		try {  
			long fileLength = new File(downLoadPath).length();  
			response.setContentType("application/x-msdownload;");  
			response.setHeader("Content-disposition", "attachment; filename="  
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
			response.setHeader("Content-Length", String.valueOf(fileLength));  
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
			bos = new BufferedOutputStream(response.getOutputStream());  

			byte[] buff = new byte[2048];  
			int bytesRead;  
			//遍历出文件流 并输出
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
				bos.write(buff, 0, bytesRead);  
			}  
		} catch (Exception e) {  
			e.printStackTrace();  
		} finally {  
			if (bis != null)  
				bis.close();  
			if (bos != null)  
				bos.close();  
		}  
		return null;  
	}
	
	
	@RequestMapping("dowFee")
	@ResponseBody
	public String downloadExecleFee(String fileName,HttpServletRequest request ,HttpServletResponse response) throws Exception{

		response.setContentType("text/html;charset=utf-8");  
		request.setCharacterEncoding("UTF-8");  
		java.io.BufferedInputStream bis = null;  
		java.io.BufferedOutputStream bos = null;  
		//获取文件的位置
		String ctxPath = request.getSession().getServletContext().getRealPath(  
		"/")  
		+ "model\\importTemplateFee\\";  
		String downLoadPath = ctxPath + fileName;  
		System.out.println("downLoadPath="+downLoadPath);  
		try {  
			long fileLength = new File(downLoadPath).length();  
			response.setContentType("application/x-msdownload;");  
			response.setHeader("Content-disposition", "attachment; filename="  
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));  
			response.setHeader("Content-Length", String.valueOf(fileLength));  
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
			bos = new BufferedOutputStream(response.getOutputStream());  

			byte[] buff = new byte[2048];  
			int bytesRead;  
			//遍历出文件流 并输出
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
				bos.write(buff, 0, bytesRead);  
			}  
		} catch (Exception e) {  
			e.printStackTrace();  
		} finally {  
			if (bis != null)  
				bis.close();  
			if (bos != null)  
				bos.close();  
		}  
		return null;  
	}
	/***
	 * 发行的批量修改的功能模块
	 * @param plParam
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/fxPlSet")
	@ResponseBody
	public ReturnObject setFxPl(String plParam,HttpServletRequest request,HttpSession session) throws Exception{
		ReturnObject returnObject=new ReturnObject();
		JSONObject jsonPlParam = JSONObject.fromObject(plParam);
		JSONArray plRows=jsonPlParam.getJSONArray("plRows");
		String plFlag=jsonPlParam.getString("plFlag");
		String zDsId=jsonPlParam.getString("zDsId");
		String dsId=jsonPlParam.getString("dsId");
		String djId=jsonPlParam.getString("djId");
		String pkName=jsonPlParam.getString("pkName");
		JSONObject plObj=jsonPlParam.getJSONObject("plObj");
		return singleService.setFxPl(pkName,zDsId,dsId,djId,plFlag,plObj,plRows,session);
	}
	/***
	 * 发行的批量功能
	 * @param djId
	 * @param plFlag
	 * @param plRows
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/queryProduct")
	@ResponseBody
	public List<Map<String,Object>> queryProduct(String H_ISBN,String H_NAME,String cid,HttpServletRequest request,HttpSession session) throws Exception{
		return singleService.queryProduct(H_ISBN,H_NAME);
	}

    /**
     * 根据客户名称查询是否存在相同的客户
     * @param cId
     * @param request
     * @return
     */
    @RequestMapping("sureSaveisnull")
    @ResponseBody
    public int sureSaveisnull(String NAME,String ccid,HttpServletRequest request){
        int bool= singleService.sureSaveisnull(NAME,ccid);
        return bool;
    }

	@RequestMapping("cwygrkSaveisnull")
	@ResponseBody
	public int cwygrkSaveisnull(String H_ID,String YGR_ID,HttpServletRequest request){
		int bool= singleService.cwygrkSaveisnull(H_ID,YGR_ID);
		return bool;
	}

    /**
     * 客户实销上报（按日）的导入
     * @param flag
     * @param request
     * @param session
     * @return lhl
     * @throws Exception
     */
    @RequestMapping("/pageToImportkh")
    public String pageToImportkh(String dsid,String kvs,String flag,HttpServletRequest request,HttpSession session) throws Exception{
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("dsid", dsid);
            map.put("kvs", kvs);
            map.put("flag", flag);
            session.setAttribute("data",map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "model/cwImportExcel/fxclientsalesbyday";
    }

    //连接到导入界面
    @RequestMapping("improtjspfc")
    public String returnimprotjspfx(){
        return "model/cwImportExcel/fxclientsalesbyday";
    }
    //把导入的信息处理后返回到界面
    @SuppressWarnings("unchecked")
    @RequestMapping("/improtRetunInfofc")
    @ResponseBody
    public  QueryJson getImprotInfofc(SingleParam sp, HttpServletRequest request ) throws IOException{
        String keys = request.getParameter("keys");
        String flg = keys.split("/")[0];
        String dsid = keys.split("/")[1];
        String kvs = keys.split("/")[2];
        sp.setUrl(sp.getFile().getOriginalFilename());
        sp.setInputStram(sp.getFile().getInputStream());
        QueryJson queryJson=new QueryJson();
        queryJson.setJson(singleService.getReturnImproInfofc(flg, dsid, kvs, sp));
        return   queryJson;
    }
    /**
     * 删除商品临时表中的导入数据
     * @param sp
     * @return
     */
    @RequestMapping("delsmataOrders")
    @ResponseBody
    public boolean delsMataOrders(SingleParam sp){
        boolean bool=singleService.getDelMateOrders(sp);
        return bool;
    }

    /***
     * 弹框的查询条件
     * @param djId
     * @param plFlag
     * @param plRows
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping("/queryProductBYDAY")
    @ResponseBody
    public List<Map<String,Object>> queryProductBYDAY(String H_ISBN,String H_NAME,String cid,HttpServletRequest request,HttpSession session) throws Exception{
        return singleService.queryProductBYDAY(H_ISBN,H_NAME);
    }


    /**
     * 客户实销上报（按月）的导入
     * @param flag
     * @param request
     * @param session
     * @return lhl
     * @throws Exception
     */
    @RequestMapping("/pageToImportkhMonth")
    public String pageToImportkhMonth(String dsid,String kvs,String flag,HttpServletRequest request,HttpSession session) throws Exception{
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("dsid", dsid);
            map.put("kvs", kvs);
            map.put("flag", flag);
            session.setAttribute("data",map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "model/cwImportExcel/fxMonthSX";
    }

	/**
	 * 客户在途上报（按月）
	 * @param flag
	 * @param request
	 * @param session
	 * @return lhl
	 * @throws Exception
	 */
	@RequestMapping("/pageToImportZTMonth")
	public String pageToImportZTMonth(String dsid,String kvs,String flag,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dsid", dsid);
			map.put("kvs", kvs);
			map.put("flag", flag);
			session.setAttribute("data",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "model/cwImportExcel/fxMonthZT";
	}

	/**
	 * 客户差异消耗上报（按月）
	 * @param flag
	 * @param request
	 * @param session
	 * @return lhl
	 * @throws Exception
	 */
	@RequestMapping("/pageToImportCYXHMonth")
	public String pageToImportCYXHMonth(String dsid,String kvs,String flag,HttpServletRequest request,HttpSession session) throws Exception{
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("dsid", dsid);
			map.put("kvs", kvs);
			map.put("flag", flag);
			session.setAttribute("data",map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "model/cwImportExcel/fxMonthCYXH";
	}

    //连接到导入界面
//    @RequestMapping("improtjspfc")
//    public String returnimprotjspfx(){
//        return "model/cwImportExcel/fxMonthSx";
//    }
    //把导入的信息处理后返回到界面
    @SuppressWarnings("unchecked")
    @RequestMapping("/improtRetunInfofcbyMonth")
    @ResponseBody
    public  QueryJson improtRetunInfofcbyMonth(SingleParam sp, HttpServletRequest request ) throws IOException{
        String keys = request.getParameter("keys");
        String flg = keys.split("/")[0];
        String dsid = keys.split("/")[1];
        String kvs = keys.split("/")[2];
        sp.setUrl(sp.getFile().getOriginalFilename());
        sp.setInputStram(sp.getFile().getInputStream());
        QueryJson queryJson=new QueryJson();
        queryJson.setJson(singleService.getReturnImproInfofcByMonth(flg, dsid, kvs, sp));
        return   queryJson;
    }

    /**
     * 删除商品临时表中的导入数据
     * @param sp
     * @return
     */
    @RequestMapping("delsmataOrdersfms")
    @ResponseBody
    public boolean delsmataOrdersfms(SingleParam sp){
        boolean bool=singleService.delsmataOrdersfms(sp);
        return bool;
    }
}